const products = require('../../utils/products');
const computedBehavior = require('miniprogram-computed').behavior;
Component({
  behaviors:[computedBehavior],
  data:{
    products,
    allChecked:false
  },
  methods:{
    // 数量减少
    desc(e){
      const {index} = e.currentTarget.dataset;
      // 临界值判断
      if(this.data.products[index].num <= 1){
        this.data.products[index].num=1
        return;
      } 
      --this.data.products[index].num;
      // 更新视图
      this.setData({products:this.data.products})
    },
    // 数量增加
    asc(e){
      // 通常需要跟库存做对比
      const {index} = e.currentTarget.dataset;
      this.data.products[index].num++;
      // 更新视图
      this.setData({products:this.data.products})
    },
    // 删除商品
    _cartDelete(e){
      const {index} = e.currentTarget.dataset;
      this.data.products.splice(index,1);
      this.setData({products:this.data.products});
    },
    // 全选和反选
    _changeAllChecked(e){
      this.data.products.forEach(item=>{
        item.checked = e.detail.value;
      });
      this.setData({products:this.data.products});
    },
    // 每一个复选框都选选中时,全选选中,
    // 有一个复选框不选中时,全选不选中
    _changeChecked(e){
      const {index} = e.currentTarget.dataset;
      this.data.products[index].checked = e.detail.value;
      const status = this.data.products.every(item=>item.checked);
      // 更新全选选中值
      this.setData({allChecked:status});
    }
  },
  computed:{
    totalPrice(data){
      let sum = 0;
      data.products.forEach(item=>{
        if(item.checked){
          sum += item.num * item.price;
        }
      })
      return sum.toFixed(2)
    },
    totalNum(data){
      let num = 0;
      data.products.forEach(item=>{
        if(item.checked){
          num += item.num;
        }
      })
      return num;
    }
  }
})
